import gtk, gobject
import json
import time
import ConfigParser
import pycurl
import os

class Lingrab:
	def __init__(self):
		self.json = ""
		
		self.home = os.path.expanduser("~")

		# Make sure we have a config file
		self.config = ConfigParser.RawConfigParser()

		if not os.path.exists(self.home+"/.lingrabrc"):
			# Nope, so let's make one
			self.config.add_section("paths")
			self.config.set("paths","watch_path", self.home+"/Desktop/screenshot1.png")
			
			# Now write it to the file
			with open(self.home+"/.lingrabrc","wb") as configfile:
				self.config.write(configfile)
		else:
			self.config.read(self.home+"/.lingrabrc")


	
	def uploadImage(self, path):
		# Set the status icon to busy
		self.statusIcon.set_from_file("img/lin_busy.png")
		
		# Create new pycurl instance
		cu = pycurl.Curl()
		
		# Set the POST variables to the image and dev key
		vals = [
			("key","34deec465d2fc17f6606df690bae2048"),
			("image", (cu.FORM_FILE, path))
		]
		
		# Set the URL to send to
		cu.setopt(cu.URL, "http://imgur.com/api/upload.json")
		# This lets us get the json returned by imgur
		cu.setopt(cu.WRITEFUNCTION, self.resp_callback)
		cu.setopt(cu.HTTPPOST, vals)
		
		# Do eet!
		cu.perform()
		cu.close()
		
		# Set the status icon to done...
		self.statusIcon.set_from_file("img/lin_done.png")
		# Wait 3 seconds and then set the icon to idle
		gobject.timeout_add(3000, self.statusIcon.set_from_file, "img/lin_idle.png")

	# Used for getting the response json from imgur
	def resp_callback(self, buff):
		self.json += buff
	
	# Extracts the image URL from the json data
	def getURL(self):
		js = json.loads(self.json)
		return js['rsp']['image']['original_image']
	
	# Inserts the text variable into the clipboard
	def toClipboard(self, text):
		cb = gtk.Clipboard()
		cb.set_text(text)
		cb.store()
	
	def shotLoop(self):
		path = self.config.get("paths","watch_path")
		if(os.path.exists(path)):
			print "Screenshot found, uploading!"
			self.uploadImage(path)
			url = self.getURL()
			self.toClipboard(url)
			print "Done! Screenshot uploaded without errors!"

			# Do some housecleaning
			os.remove(path)
			self.json = ""
		
		return True

	# Initiates the GUI elements of Linup
	def gtkInit(self):
		self.statusIcon = gtk.StatusIcon()
		self.statusIcon.set_from_file("img/lin_idle.png")
